# 股票数据处理模块

import pandas as pd
import numpy as np
from typing import Dict, List, Union, Optional
import logging
from .api import AKShareAPI
from .technical_indicators import TechnicalIndicators
from datetime import datetime, timedelta
from src.database.data_manager import DataManager
from src.utils.logger_manager import log, err
import time
import random

from src.utils.utils import are_dates_in_same_week
logger = logging.getLogger(__name__)

class StockDataProcessor:
    """
    股票数据处理类，提供数据分析和处理功能
    """
    def __init__(self):
        self.api = AKShareAPI()
        self.indicators = TechnicalIndicators()
        # 添加股票列表属性
        self.all_stocks = []
        self.tech_stocks = []
        self.st_stocks = []
        self.normal_stocks = []
        # 添加交易日信息的类属性
        self.trading_days = []
        # 初始化数据管理器
        self.data_manager = DataManager.get_instance()
        # 检查并初始化数据
        self.initialize_data()

    def initialize_data(self) -> bool:
        """初始化数据，检查并更新股票数据"""
        try:
            # 检查Redis中的股票列表更新时间
            last_update = self.data_manager.redis.get('stock_list:update_time')
            current_date = datetime.now().strftime('%Y%m%d')
            # 初始化交易日信息
            self._init_trading_days()
            
            # 如果今天已经更新过，直接加载数据
            if (last_update and last_update.startswith(current_date)) or not self._is_trading_day(datetime.now()):
                logger.info("今日股票数据已更新")
                # 加载已有数据
                self._load_stock_lists()
            else:
                # 获取并更新股票列表
                logger.info("从API获取最新股票列表")
                self.get_stock_list()
            
            # 检查股票列表是否加载成功
            if not self.all_stocks:
                logger.error("股票列表为空，初始化失败")
                return False
            
            # 判断是否需要初始化历史数据
            historical_data_status = self.data_manager.redis.get('stock_history:initialized')
            if (historical_data_status != 'true'):
                logger.info("历史数据未初始化，开始初始化历史数据")
                self._initialize_historical_data()
                self.data_manager.redis.set('stock_history:initialized', 'true')
            else:
                logger.info("历史数据已初始化，无需重复初始化")
            
            logger.info("股票数据初始化完成")
            return True
        except Exception as e:
            logger.error(f"初始化股票数据失败: {str(e)}")
            return False

    def _init_trading_days(self) -> None:
        """初始化交易日信息"""
        try:
            # 从Redis获取交易日历并反序列化
            trading_days_str = self.data_manager.redis.get('market:trading_days')
            if (trading_days_str):
                self.trading_days = trading_days_str.split(',')
            
            if not self.trading_days:
                logger.info("Redis中不存在交易日历，从API获取")
                # 获取交易日历
                trading_df = self.api.get_trading_holidays()
                if trading_df.empty:
                    err("获取交易日历失败")
                    return
                    
                # trade_date是datetime.date对象，直接格式化
                self.trading_days = [d.strftime('%Y%m%d') for d in trading_df['trade_date']]
                
                # 将数组转换为字符串存储到Redis
                trading_days_str = ','.join(self.trading_days)
                self.data_manager.redis.set('market:trading_days', trading_days_str)
                logger.info(f"成功获取并缓存{len(self.trading_days)}个交易日信息")
            
            logger.info(f"交易日信息初始化完成，共{len(self.trading_days)}个交易日")
                
        except Exception as e:
            logger.error(f"初始化交易日信息失败: {str(e)}")
    def _initialize_historical_data(self) -> None:
        """初始化历史数据"""
        try:
            # 继续处理每支股票的历史数据
            for stock in self.all_stocks:
                symbol = stock['code']
                name = stock['name']
                
                # 跳过*ST股票  689009有错误数据
                if symbol.startswith('400') or symbol == '689009':
                    logger.debug(f"跳过退市股票/不正常数据的股票: {symbol} {name}")
                    continue
                # 防止数据出错，从数据库获取最后更新日期
                df = self.data_manager.query_stock_prices(
                    symbol=symbol,
                    limit=1,
                    order_by='end_date DESC'
                )                
                if df.empty:
                    # 如果没有记录，则获取所有历史数据
                    logger.info(f"股票 {symbol} 没有记录，开始获取数据...")
                    self._update_stock_history(symbol)
                else:
                    # 获取最后更新日期的后一天
                    last_date = pd.to_datetime(df['end_date'].iloc[0])
                    next_date = last_date + timedelta(days=1)
                    current_date = datetime.now()
                    
                    # 如果后一天小于今天，检查是否为交易日
                    if next_date.date() < current_date.date():
                        # 检查是否为交易日
                        if self._is_trading_day(next_date):
                            logger.info(f"股票 {symbol} 存在新的交易日数据，更新数据...")
                            self._update_stock_history(symbol, start_date=next_date.strftime('%Y%m%d'))
                        else:
                            logger.debug(f"股票 {symbol} 无需更新")
                
        except Exception as e:
            logger.error(f"初始化历史数据失败: {str(e)}")

    def _is_trading_day(self, date: datetime) -> bool:
        """判断是否为交易日"""
        try:
            # 确保 date 转换为字符串格式与 trading_days 一致
            check_date = date.strftime('%Y%m%d')
            return check_date in self.trading_days
        except Exception as e:
            logger.error(f"检查交易日失败: {str(e)}")
            return True  # 出错时默认为交易日

    def _process_period_data(self, data: pd.DataFrame) -> None:
        """
        处理股票历史数据，计算并存储日、周、月数据，同时计算并存储技术指标。
        """
        try:
            # 将换手率扩大100倍
            if 'turnover' in data.columns:
                data['turnover'] = data['turnover'] * 100

            # 确保数据按日期排序
            data = data.sort_values('date')
            data['start_date'] = data['date']
            data['end_date'] = data['date']
            # 传入需要保存数据的最早日期
            self._process_period_d_data(data)
            self._process_period_w_data(data)
            self._process_period_m_data(data)

        except Exception as e:
            logger.error(f"处理历史数据失败: {str(e)}")
            
    def _process_period_d_data(self, data: pd.DataFrame) -> None:
        symbol = data['symbol'].iloc[0]
        period = 'd'
        d_data = self.get_60stock_data_by_period(symbol, period)
        if not d_data.empty:
            # 将获取的最近60条数据与当前数据合并
            d_data = pd.concat([d_data, data], ignore_index=True)
            d_data = d_data.drop(columns=['date'], errors='ignore')  # 忽略不存在的列
            d_data = d_data.drop_duplicates(subset=['start_date'], keep='last')
        else:
            d_data = data.copy()

        # 数据标准化并存储日数据
        data['period'] = period
        d_data['period'] = period
        self.data_manager.store_stock_prices(data)
        self._calculate_and_store_indicators(d_data, data['start_date'].min())

    def _process_period_w_data(self, data: pd.DataFrame) -> None:
        # 计算并存储周数据
        weekly_data = []
        current_week = []
        period = 'w'
        for _, row in data.iterrows():
            if not current_week:
                current_week.append(row)
            else:
                if are_dates_in_same_week(current_week[-1]['start_date'], row['start_date']):
                    current_week.append(row)
                else:
                    # 汇总当前周数据
                    week_df = pd.DataFrame(current_week)
                    weekly_data.append({
                        'symbol': week_df['symbol'].iloc[0],
                        'start_date': week_df['start_date'].iloc[0],
                        'end_date': week_df['end_date'].iloc[-1],
                        'period': period,
                        'open': week_df['open'].iloc[0],
                        'high': week_df['high'].max(),
                        'low': week_df['low'].min(),
                        'close': week_df['close'].iloc[-1],
                        'volume': week_df['volume'].sum(),
                        'amount': week_df['amount'].sum(),
                        'turnover': week_df['turnover'].mean()
                    })
                    current_week = [row]

        # 处理最后一周
        if current_week:
            week_df = pd.DataFrame(current_week)
            weekly_data.append({
                'symbol': week_df['symbol'].iloc[0],
                'start_date': week_df['start_date'].iloc[0],
                'end_date': week_df['end_date'].iloc[-1],
                'period': period,
                'open': week_df['open'].iloc[0],
                'high': week_df['high'].max(),
                'low': week_df['low'].min(),
                'close': week_df['close'].iloc[-1],
                'volume': week_df['volume'].sum(),
                'amount': week_df['amount'].sum(),
                'turnover': week_df['turnover'].mean()
            })
        
        symbol = data['symbol'].iloc[0]
        w_data = self.get_60stock_data_by_period(symbol, period)
        if not w_data.empty:
            # 检查是否为同一周
            if are_dates_in_same_week(w_data.iloc[-1]['start_date'], weekly_data[0]['start_date']):
                last_week = w_data.iloc[-1]
                first_new_week = weekly_data[0]
                updated_week = {
                    'id': last_week['id'],
                    'symbol': last_week['symbol'],
                    'start_date': last_week['start_date'],
                    'end_date': first_new_week['end_date'],
                    'period': period,
                    'open': last_week['open'],
                    'high': max(last_week['high'], first_new_week['high']),
                    'low': min(last_week['low'], first_new_week['low']),
                    'close': first_new_week['close'],
                    'volume': last_week['volume'] + first_new_week['volume'],
                    'amount': float(last_week['amount']) + float(first_new_week['amount']),
                    'turnover': (float(last_week['turnover']) + float(first_new_week['turnover'])) / 2
                }
                w_data = w_data.iloc[:-1]
                weekly_data[0] = updated_week

        # 合并新数据
        weekly_df = pd.DataFrame(weekly_data)
        w_data = pd.concat([w_data, weekly_df], ignore_index=True)

        self.data_manager.store_stock_prices(weekly_df)  # 存储周数据
        self._calculate_and_store_indicators(w_data, data['start_date'].min())

    def _process_period_m_data(self, data: pd.DataFrame) -> None:
        # 计算并存储月数据
        monthly_data = []
        current_month = []
        period = 'm'
        for _, row in data.iterrows():
            if not current_month:
                current_month.append(row)
            else:
                if row['start_date'].month == current_month[-1]['start_date'].month:
                    current_month.append(row)
                else:
                    # 汇总当前月数据
                    month_df = pd.DataFrame(current_month)
                    monthly_data.append({
                        'symbol': month_df['symbol'].iloc[0],
                        'start_date': month_df['start_date'].iloc[0],
                        'end_date': month_df['end_date'].iloc[-1],
                        'period': period,
                        'open': month_df['open'].iloc[0],
                        'high': month_df['high'].max(),
                        'low': month_df['low'].min(),
                        'close': month_df['close'].iloc[-1],
                        'volume': month_df['volume'].sum(),
                        'amount': month_df['amount'].sum(),
                        'turnover': month_df['turnover'].mean()
                    })
                    current_month = [row]

        # 处理最后一个月
        if current_month:
            month_df = pd.DataFrame(current_month)
            monthly_data.append({
                'symbol': month_df['symbol'].iloc[0],
                'start_date': month_df['start_date'].iloc[0],
                'end_date': month_df['end_date'].iloc[-1],
                'period': period,
                'open': month_df['open'].iloc[0],
                'high': month_df['high'].max(),
                'low': month_df['low'].min(),
                'close': month_df['close'].iloc[-1],
                'volume': month_df['volume'].sum(),
                'amount': month_df['amount'].sum(),
                'turnover': month_df['turnover'].mean()
            })

        
        symbol = data['symbol'].iloc[0]
        m_data = self.get_60stock_data_by_period(symbol, period)
        if not m_data.empty:
            # 检查是否为同一月
            if m_data.iloc[-1]['start_date'].month == monthly_data[0]['start_date'].month:
                last_month = m_data.iloc[-1]
                first_new_month = monthly_data[0]
                monthly_df = {
                    'id': last_month['id'],
                    'symbol': last_month['symbol'],
                    'start_date': last_month['start_date'],
                    'end_date': first_new_month['end_date'],
                    'period': period,
                    'open': last_month['open'],
                    'high': max(last_month['high'], first_new_month['high']),
                    'low': min(last_month['low'], first_new_month['low']),
                    'close': first_new_month['close'],
                    'volume': last_month['volume'] + first_new_month['volume'],
                    'amount': float(last_month['amount']) + float(first_new_month['amount']),
                    'turnover': (float(last_month['turnover']) + float(first_new_month['turnover'])) / 2
                }
                m_data = m_data.iloc[:-1]
                monthly_data[0] = monthly_df
            
        # 合并新数据
        monthly_df = pd.DataFrame(monthly_data)
        m_data = pd.concat([m_data, monthly_df], ignore_index=True)
        self.data_manager.store_stock_prices(monthly_df)  # 存储月数据
        self._calculate_and_store_indicators(m_data, data['start_date'].min())
            
    def get_60stock_data_by_period(self, symbol: str, period: str) -> pd.DataFrame:
        # 获取最近的60条数据并合并到当前数据
        recent_data = self.data_manager.query_stock_prices(
            symbol=symbol,
            con = {'period = ':period},
            limit=60,
            order_by='start_date DESC'
        )
        if not recent_data.empty:
            # 转换为 DataFrame 格式，并确保 date 列等于 start_date
            recent_data = pd.DataFrame(recent_data)
            recent_data = recent_data.drop(columns=['created_at'])
            recent_data = recent_data.sort_values(by='start_date', ascending=True, inplace=False).reset_index(drop=True)
            
        return recent_data

    def _calculate_and_store_indicators(self, data: pd.DataFrame, min_date: str) -> None:
        """
        计算技术指标并存储到技术指标表，仅插入新增的数据。

        Args:
            data (pd.DataFrame): 包含股票价格数据的DataFrame。
            min_date (str): 最小日期，用于筛选需要保存的数据。
        """
        try:
            # 确保 start_date 和 end_date 为 datetime 类型
            if not pd.api.types.is_datetime64_any_dtype(data['start_date']):
                data['start_date'] = pd.to_datetime(data['start_date'], errors='coerce')
            if not pd.api.types.is_datetime64_any_dtype(data['end_date']):
                data['end_date'] = pd.to_datetime(data['end_date'], errors='coerce')
            
            # 获取存储后的 stock_prices 表的 ID
            stored_data = self.data_manager.query_stock_prices(
                symbol=data['symbol'].iloc[0],
                start_date=data['start_date'].min(),
                end_date=data['end_date'].max(),
                con={'period = ': data['period'].iloc[0]},
            )

            if stored_data.empty:
                logger.warning("未找到存储的股票价格数据，无法计算技术指标")
                return

            # 计算技术指标
            indicators_data = self.indicators.analyze_data(stored_data)

            # 确保 min_date 和 indicators_data['end_date'] 类型一致
            min_date = pd.Timestamp(min_date).date()
            indicators_data['end_date'] = pd.to_datetime(indicators_data['end_date'], errors='coerce').dt.date
            # 准备插入技术指标表的数据
            indicators_data['price_id'] = stored_data['id']

            # 筛选出 end_date 大于或等于 min_date 的数据并重置索引
            indicators_data = indicators_data[indicators_data['end_date'] >= min_date].reset_index(drop=True)

            if indicators_data.empty:
                logger.info("没有新增的技术指标数据需要存储")
                return


            self.data_manager.store_technical_indicators(indicators_data)

            logger.info(f"成功计算并存储新增技术指标，共{len(indicators_data)}条记录")
        except Exception as e:
            logger.error(f"计算或存储技术指标失败: {str(e)}")

    def _update_stock_history(self, symbol: str, start_date: Optional[str] = None) -> bool:
        """更新单个股票的历史数据
        
        Args:
            symbol: 股票代码
            start_date: 开始日期，格式'YYYYMMDD'
        """
        try:
            end_date = datetime.now().strftime('%Y%m%d')
            
            # 获取历史数据
            history_data = self.api.get_stock_daily(symbol, start_date, end_date)
            if history_data.empty:
                err(f"获取股票{symbol}历史数据为空")
                return False
            
            history_data['symbol'] = symbol
            history_data = history_data.drop(columns=['outstanding_share'])
            
            # 处理日、周、月数据
            self._process_period_data(history_data)
            
            return True
        except Exception as e:
            logger.error(f"更新股票 {symbol} 历史数据失败: {str(e)}")
            return False

    def _load_stock_lists(self):
        """从Redis加载各类股票列表"""
        try:
            # 使用通用的get方法获取股票列表
            stocks_data = self.data_manager.redis.get('stock_list:all_stocks')
            self._classify_stocks(stocks_data)
            # 更新实例属性
            # self.tech_stocks = classified_stocks['tech'].to_dict('records')
            # self.st_stocks = classified_stocks['st'].to_dict('records')
            # self.normal_stocks = classified_stocks['normal'].to_dict('records')
            # self.all_stocks = classified_stocks['all'].to_dict('records')
            
            logger.info(f"股票列表加载完成：全部 {len(self.all_stocks)} 只，"
                        f"科创板 {len(self.tech_stocks)} 只，"
                        f"ST {len(self.st_stocks)} 只，"
                        f"普通 {len(self.normal_stocks)} 只")
        except Exception as e:
            logger.error(f"加载股票列表失败: {str(e)}")

    def _classify_stocks(self, stocks_df: pd.DataFrame) -> Dict[str, pd.DataFrame]:
        """对股票进行分类"""
        try:
            # 对于从Redis加载的数据需要先转换为DataFrame
            if isinstance(stocks_df, list):
                df = pd.DataFrame(stocks_df)
            else:
                df = stocks_df.copy()
            
            # 首先过滤掉退市股票（400开头）
            mask = ~df['code'].astype(str).str.startswith('400')
            df = df[mask]
            
            # 添加类型列
            df['type'] = 'normal'  # 默认为普通股票
            
            # 1. 识别科创板股票 (688开头或689开头)
            tech_mask = df['code'].str.startswith(('688', '689'))
            df.loc[tech_mask, 'type'] = 'tech'
            
            # 2. 识别ST股票（包括*ST）
            st_mask = df['name'].str.contains(r'\*?ST', regex=True, na=False)
            df.loc[st_mask, 'type'] = 'st'
            
            # 分别获取不同类型的股票
            self.tech_stocks = df[df['type'] == 'tech'].to_dict('records')
            self.st_stocks = df[df['type'] == 'st'].to_dict('records')
            self.normal_stocks = df[(df['type'] == 'normal') & 
                                    ~(df['code'].str.startswith(('8', '4', '920')))].to_dict('records')
            
            # 更新实例属性
            self.all_stocks = df.to_dict('records')
            filtered_count = len(stocks_df) - len(df)
            bei_count = len(df[df['type'] == 'normal']) - len(self.normal_stocks)
            
            # 记录分类统计信息
            logger.info(f"股票分类完成：全部 {len(self.all_stocks)} 只，"
                        f"科创板 {len(self.tech_stocks)} 只，"
                        f"ST {len(self.st_stocks)} 只，"
                        f"普通 {len(self.normal_stocks)} 只")
            if filtered_count > 0:
                logger.info(f"过滤掉 {filtered_count} 只退市股票")
            if bei_count > 0:
                logger.info(f"从普通股票中过滤掉 {bei_count} 只北交所股票")
            
            return {
                'all': self.all_stocks,
                'tech': self.tech_stocks,
                'st': self.st_stocks,
                'normal': self.normal_stocks
            }
            
        except Exception as e:
            logger.error(f"股票分类失败: {str(e)}")
            return {}

    def get_stock_list(self) -> pd.DataFrame:
        """获取处理后的股票列表，并按类型分类和存储"""
        try:
            # 获取所有股票列表
            all_stocks = self.api.get_stock_list()
            if all_stocks.empty:
                return pd.DataFrame()
            
            # 对股票进行分类
            classified_stocks = self._classify_stocks(all_stocks)
            if not classified_stocks:
                return pd.DataFrame()
            
            # 使用通用的set方法存储股票列表到Redis
            self.data_manager.redis.set('stock_list:all_stocks', self.all_stocks)
            
            # 更新最后更新时间
            self.data_manager.redis.set('stock_list:update_time', 
                datetime.now().strftime('%Y%m%d %H:%M:%S'))
            
            # 更新到PostgreSQL
            self.data_manager.update_stock_list(classified_stocks['all'])
            
            # 记录统计信息
            logger.info(f"股票分类统计: 科创板{len(self.tech_stocks)}只，"
                       f"ST股票{len(self.st_stocks)}只，普通股票{len(self.normal_stocks)}只，"
                       f"总计{len(self.all_stocks)}只")
            
            return classified_stocks['all']
            
        except Exception as e:
            logger.error(f"处理股票列表失败: {str(e)}")
            return pd.DataFrame()

    def update_newest_data(self, input_date: Optional[str] = None) -> bool:
        """更新行情数据"""
        try:
            # 获取当前时间和日期，支持传入日期参数
            now = datetime.strptime(input_date, '%Y%m%d') if input_date else datetime.now()
            current_time = now.strftime('%H:%M:%S')

            # 检查 Redis 中的最后更新时间标志
            last_update_time = self.data_manager.redis.get('stock_data:last_update_time')
            if last_update_time:
                last_update_time = datetime.strptime(last_update_time, '%Y-%m-%d %H:%M:%S')
                # 检查是否在前天16:00:00到今天16:00:00之间
                if last_update_time >= (now - timedelta(days=2)).replace(hour=16, minute=0, second=0) and \
                   last_update_time < now.replace(hour=16, minute=0, second=0) and \
                   current_time < '16:00:00':
                    # 检查最后更新时间和今天之间是否存在交易日
                    for date in pd.date_range(last_update_time.date(), now.date()):
                        if self._is_trading_day(date):
                            break
                    else:
                        logger.info("今日数据已更新，无需重复更新")
                        return False

            # 获取今日实时行情数据
            today_data = self.api.stock_zh_a_spot_em()
            if today_data.empty:
                err("未能获取今日实时行情数据")
                return False
            # 遍历 today_data 今天历史行情数据的所有股票
            for _, stock_data in today_data.iterrows():
                symbol = stock_data['代码']
                # 构造更新数据
                update_data = {
                    'symbol': symbol,
                    'date': now.strftime('%Y%m%d'),
                    'period': 'd',
                    'open': stock_data['今开'],
                    'high': stock_data['最高'],
                    'low': stock_data['最低'],
                    'close': stock_data['最新价'],
                    'volume': stock_data['成交量'],
                    'amount': stock_data['成交额'],
                    'turnover': stock_data['换手率']/100
                }
                try:
                    # 查询数据库中是否存在今天的历史行情数据
                    existing_data = self.data_manager.query_stock_prices(
                        symbol=symbol,
                        limit=1,
                        con = {'period = ':'d'},
                        order_by='end_date DESC'
                    )

                    if not existing_data.empty:
                        # 检查最近的 end_date 是否是今天的上一个交易日
                        last_end_date = pd.to_datetime(existing_data['end_date'].iloc[0]).strftime('%Y%m%d')
                        now_date = now.strftime('%Y%m%d')

                        # 找到今天的上一个交易日
                        if now_date in self.trading_days:
                            today_index = self.trading_days.index(now_date)
                            previous_trading_day = self.trading_days[today_index - 1] if today_index > 0 else None
                        else:
                            log(f"今天 {now_date} 不在交易日列表中")

                        if last_end_date == previous_trading_day:
                            self._process_period_data(pd.DataFrame([update_data]))
                        else:
                            err(f"股票 {symbol} 的最近交易日数据未更新到 {previous_trading_day}，开始更新历史数据...")
                    else:
                        # 如果不存在，则用 self._update_stock_history 更新
                        log(f"股票 {symbol} 的今日数据不存在，开始更新历史数据...")
                        self._update_stock_history(symbol)

                except Exception as e:
                    err(f"处理股票 {symbol} 数据失败: {str(e)}")
                    continue

                logger.info(f"成功更新股票 {symbol} 的今日行情数据")

            # 更新 Redis 中的最后更新时间标志
            self.data_manager.redis.set('stock_data:last_update_time', now.strftime('%Y-%m-%d %H:%M:%S'))
            logger.info("今日数据更新完成")
            return True

        except Exception as e:
            logger.error(f"更新今日数据失败: {str(e)}")
            return False

    def store_stock_prices(self, data: pd.DataFrame):
        """存储股票价格数据"""
        try:
            table_name = 'stock_prices'
            if data.empty:
                logger.warning("数据为空，无法存储股票价格数据")
                return

            # 检查是否存在 start_date 和 end_date 列
            if 'start_date' not in data.columns:
                data['start_date'] = data['date']
            if 'end_date' not in data.columns:
                data['end_date'] = data['date']

            # 检查 start_date 和 end_date 的类型并转换为 datetime.date
            if not pd.api.types.is_datetime64_any_dtype(data['start_date']):
                data['start_date'] = pd.to_datetime(data['start_date'], errors='coerce').dt.date
            else:
                data['start_date'] = data['start_date'].dt.date
            if not pd.api.types.is_datetime64_any_dtype(data['end_date']):
                data['end_date'] = pd.to_datetime(data['end_date'], errors='coerce').dt.date
            else:
                data['end_date'] = data['end_date'].dt.date

            # 删除 'date' 列
            if 'date' in data.columns:
                data = data.drop(columns=['date'])

            # 存储数据到数据库
            self.data_manager.store_stock_prices(data)
            logger.info("股票价格数据存储成功")
        except Exception as e:
            logger.error(f"存储股票价格数据失败: {str(e)}")
